import {getUserAvatarImage, getAdvisorAvatarImage} from './avatar_utils'
import {time_length} from './unixtime_utils'

const app = getApp()

function _get_openId(){//从本地存储获得已登录的用户的id，记为【openId】
  wx.setStorageSync('openId', 6)//待修改为在登录的时候存入
  wx.setStorageSync('openPassword', '123')//待修改为在登录的时候存入
  var openId = wx.getStorageSync('openId')
  var openPassword = wx.getStorageSync('openPassword')
  app.globalData.openId = openId
  app.globalData.openPassword = openPassword
}

//===已完成===
function get_userInfo(){//由【openId】向服务器获取【userInfo】
  _get_openId()
  let openId = app.globalData.openId
  let openPassword = app.globalData.openPassword
  console.log("==========openId:"+openId+"==========");

  wx.request({
    url: 'http://127.0.0.1:8080/api/counseling/customer/detail',
    data:{
      "customerId": openId
    },
    method: 'POST',
    success(res){
      console.log("==========get_userInfo success==========")
      console.log(res.data)
      app.globalData.userInfo['image']=getUserAvatarImage(res.data.payload.id)
      app.globalData.userInfo['id']=''+res.data.payload.id
      app.globalData.userInfo['name']=res.data.payload.name
      app.globalData.userInfo['phone']=res.data.payload.phone
      app.globalData.userInfo['password']=openPassword
      app.globalData.userInfo['emergency_name']=res.data.payload.contactName
      app.globalData.userInfo['emergency_phone']=res.data.payload.contactPhone

      wx.event.emit('get_userInfo_and_save_to_global')
    },
    fail(res){
      console.log("==========get_userInfo fail==========")
    }
  })
}

//===已完成===
function get_list(userId){//由【userId】向服务器获取咨询记录列表，分别提取出历史咨询记录列表【list】，和当前正在进行的咨询【nowAdvising】
  wx.request({
    url: 'http://127.0.0.1:8080/api/consulting/chat/record/list',
    method:'POST',
    data:{
      "callerId": app.globalData.userInfo.id,
      "start": 0,
      "length":10
    },
    success(res){
      console.log(res.data)
      var advisorInfo={}, advising = {}
      var list = []
      for(var i=0; i<res.data.payload.length; i++){
        advisorInfo={}
        advisorInfo['id']=res.data.payload[i].consultant.consultant_id
        advisorInfo['name']=res.data.payload[i].consultant.name
        advisorInfo['image']=getAdvisorAvatarImage(res.data.payload[i].consultant.sex)
        advisorInfo['online']=res.data.payload[i].consultant.is_alive

        advising={}
        advising['advisorInfo']=advisorInfo
        advising['created']=parseInt(res.data.payload[i].chat.startTime/1000)
        advising['ended']=parseInt(res.data.payload[i].chat.endTime/1000)
        advising['score']=res.data.payload[i].chat.score

        if(advising['ended']>=advising['created']&&advising['score']!=null){
          list.push(advising)
        }else{
          app.globalData.isAdvising=true
          app.globalData.nowAdvising=advising
          app.globalData.chatId=res.data.payload[i].chat.id

          console.log("==========nowAdvising chatId:"+app.globalData.chatId+"==========")
        }
      }
      console.log(list);
      app.globalData.list = list.reverse()
      wx.event.emit("get_list_and_set_to_global")
    }
  })
}

//===已完成===
function update_userInfo(newInfo){//将用户修改好的信息【userInfo】上传至服务器
  let customerId = newInfo.id
  let name = newInfo.name
  let phone = newInfo.phone
  let password = newInfo.password
  let contactName = newInfo.emergency_name
  let contactPhone = newInfo.emergency_phone

  wx.request({
    url: 'http://127.0.0.1:8080/api/counseling/customer/edit',
    method: 'PUT',
    data:{
      "customerId": customerId,
      "name": name,
      "phone": phone,
      "password":password,
      "contactName": contactName,
      "contactPhone": contactPhone
    },
    success(res){
      console.log(res.data)
      if(res.data.result=="success"){
        app.globalData.userInfo = newInfo//若上传成功则修改全局数据globalData.userInfo
      }
    }
  })
}

//===已完成===
/**
 * 将用户创建的【nowAdvising】上传至服务器，更新相关全局数据
 * 给当前咨询师的“在线执行会话数量”+1
 */ 
function create_advising(advising){
  wx.request({//根据1.用户ID、2.咨询师ID、3.开始时间 创建咨询
    url: 'http://127.0.0.1:8080/api/consulting/chat/create',
    method:'POST',
    data:{
      "customerId": app.globalData.userInfo.id,//用户ID
      "consultantId": advising.advisorInfo.id,//咨询师ID
      "startTime": advising.start_timestamp
    },
    success(res){
      console.log(res.data);
      wx.request({//给当前咨询师的“在线执行会话数量”+1
        url: 'http://127.0.0.1:8080/consultant/addalivesessionnumber/'+advising.advisorInfo.id,
        method: 'GET',
        success(res2){
          if(res2.data.result=='success'){
            app.globalData.isAdvising = true
            app.globalData.nowAdvising = advising
            app.globalData.chatId = res.data.payload
            wx.event.emit("creat_advising_and_save_to_global")
          }
        }
      })
    }
  })
}

//===已完成===
/**
 * 将已结束的咨询【advising】上传至服务器，更新相关全局数据（保留chatId——评价完成后再置空）
 * 提交其他5个统计数据到后台：
 *   1. “咨询师今日完成咨询数”+1
 *   2. “咨询师累计完成咨询数量”+1
 *   3. 增加咨询师今日咨询时长
 *   4. 增加咨询师累计咨询时长
 *   5. “咨询师在线执行会话数量”-1
 */
function end_nowAdvising(end_timestamp){
  wx.request({//根据【chatId】结束咨询，并上传【end_timestamp】
    url: 'http://127.0.0.1:8080/api/consulting/chat/finish',
    method:'PUT',
    data:{
      "chatId": app.globalData.chatId,
      "endTime": end_timestamp
    },
    success(res){//若结束成功，则:
      //更新相关全局数据（保留chatId——评价完成后再置空）
      app.globalData.nowAdvising['ended']=parseInt(end_timestamp/1000)
      wx.event.emit("upload_end_timestamp_done")
      //提交其他4个统计数据到后台
      let nowAdvising =app.globalData.nowAdvising
      wx.request({//1. “咨询师今日完成咨询数”+1
        url: 'http://127.0.0.1:8080/consultant/incretodayConsultNumber/'+nowAdvising.advisorInfo.name,
        method:'GET',
      })
      wx.request({//2. “咨询师累计完成咨询数量”+1
        url: 'http://127.0.0.1:8080/consultant/increAllConsultNumber/'+nowAdvising.advisorInfo.name,
        method:'GET',
      })
      wx.request({//3. 增加咨询师今日咨询时长
        url: 'http://127.0.0.1:8080/consultant/incretodayConsultTime/'+nowAdvising.advisorInfo.name+'/'+time_length(nowAdvising.created, nowAdvising.ended),
        method:'GET',
      })
      wx.request({//4. 增加咨询师累计咨询时长
        url: 'http://127.0.0.1:8080/consultant/increAllConsultTime/'+nowAdvising.advisorInfo.name+'/'+time_length(nowAdvising.created, nowAdvising.ended),
        method:'GET',
      })
      wx.request({//5. “咨询师在线执行会话数量”-1
        url: 'http://127.0.0.1:8080/consultant/minusalivesessionnumber/'+nowAdvising.advisorInfo.id,
        method:'GET',
      })
    }
  })
}

//===已完成===
function upload_comment(score, comment){
  var data = {
    "chatId": app.globalData.chatId,
    "appraiser": 0,
    "grade": score,
    "appraisementFromCustomer": comment,
    "appraisementCounselor": ""
  }
  console.log(data);
  wx.request({
    url: 'http://127.0.0.1:8080/api/consulting/chat/appraise',
    method:'PUT',
    data: data,
    success(res){//若评价成功，则设置全局数据
      console.log("==========comment successfully==========");
      app.globalData.isAdvising = false
      app.globalData.nowAdvising = {}
      app.globalData.chatId = ''
      wx.event.emit("upload_comment_done")
    }
  })
}

//===已完成===
function get_advisorList(){//向服务器获取可选择的咨询师列表【advisorList】
  wx.request({
    url: 'http://127.0.0.1:8080/consultant/getAllAlive',
    method: 'GET',
    success(res){
      console.log(res)
      var advisor={}, advisorList=[]
      const list = res.data.payload

      for(var i=0; i<list.length; i++){//解析响应中的数据
        advisor={}
        advisor['id']=list[i].consultant_id+''
        advisor['name']=list[i].name
        advisor['image']=getAdvisorAvatarImage(list[i].sex)
        advisor['score']=list[i].evaluation_grade
        advisor['history']=false
        advisor['available']=list[i].is_free
        
        advisorList.push(advisor)
      }
      app.globalData.advisorList = advisorList//赋值到全局
      wx.event.emit("get_advisorList_and_save_to_global")
    }
  })
}

//===已完成===
function get_advisor_available(advisor_id){//由咨询师ID【advisor_id】向服务器获取咨询师忙碌状态【is_free】
  wx.request({
    url: 'http://127.0.0.1:8080/consultant/getByID/'+advisor_id,
    method:'GET',
    success(res){
      if(res.data.payload.is_free){
        wx.event.emit("advisor_available")
      }
    }
  })
}

module.exports={
  get_userInfo,
  get_list,
  update_userInfo,
  create_advising,
  end_nowAdvising,
  upload_comment,
  get_advisorList,
  get_advisor_available
}